package com.example.excelimport.service;

import com.alibaba.excel.EasyExcel;
import com.example.excelimport.entity.User;
import com.example.excelimport.listener.PageDataListener;
import com.example.excelimport.listener.RowCountListener;
import com.example.excelimport.util.LocalDateConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserImportService {

    @Autowired
    private UserService userService;

    // 添加setter方法解决注入问题
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void importByPageRead(String filePath) {
        // 先读取Excel的总行数
        int totalRowCount = getTotalRowCount(filePath);
        log.info("Excel总行数: {}", totalRowCount);

        int pageSize = 5000;
        int totalPage = (totalRowCount + pageSize - 1) / pageSize;

        for (int page = 1; page <= totalPage; page++) {
            List<User> dataList = readExcelByPage(filePath, page, pageSize);
            if (!dataList.isEmpty()) {
                userService.batchSaveWithTransaction(dataList);
                log.info("第 {} 页数据导入完成，共 {} 条", page, dataList.size());
            }
        }
    }

    /**
     * 获取Excel总行数
     */
    private int getTotalRowCount(String filePath) {
        RowCountListener rowCountListener = new RowCountListener();
        try {
            EasyExcel.read(filePath, User.class, rowCountListener)
                    .registerConverter(new LocalDateConverter()) // 注册转换器
                    .sheet()
                    .headRowNumber(1)
                    .doRead();
        } catch (Exception e) {
            log.error("读取Excel行数失败", e);
        }
        return rowCountListener.getRowCount();
    }

    /**
     * 分页读取Excel数据
     */
    private List<User> readExcelByPage(String filePath, int page, int pageSize) {
        List<User> result = new ArrayList<>();

        PageDataListener<User> listener = new PageDataListener<>(result, page, pageSize);

        EasyExcel.read(filePath, User.class, listener)
                .registerConverter(new LocalDateConverter()) // 注册转换器
                .sheet()
                .headRowNumber(1)
                .doRead();

        return result;
    }

}

